﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;


public partial class PlayOffsResults : System.Web.UI.Page
{
    public string HTMLOUT;
    public static Tournament oTournament;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            AjaxPro.Utility.RegisterTypeForAjax(typeof(PlayOffsResults));
            int Pk_Tournament = int.Parse(Request.QueryString["id"]);
            Session["POPk_Tournament"] = Pk_Tournament;
            Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
            Session["POpageItems"] = Convert.ToInt32(rootWebConfig.AppSettings.Settings["QualifyPagination"].Value);
            Session["POTimer"] = Convert.ToInt32(rootWebConfig.AppSettings.Settings["milisecondsToShow"].Value);
            Session["PlayoffQualifyPossitions"] = Convert.ToInt32(Application["PlayoffQualifyPossitions"]);
            LoadData(Pk_Tournament);
            oTournament = new Tournament(Pk_Tournament);
           

        }
        catch (Exception) { 
        
        } 
     
    }
    public void LoadData(int Pk_Tournament) { 
            Tournament oTournament = new Tournament(Pk_Tournament);
            int Rondas = oTournament.PlayOffsRounds;
            PlayoffRounds oQualifyRounds = new PlayoffRounds(Pk_Tournament);
            //oQualifyRounds.Rounds.Sort(new ObjectComparer<QualifyRound>("PlayerNumber ASC, Round_Number ASC", true));
            int[] Scores = (int[])Session["PlayOffsScores"];
          
            List<PlayoffRound> RoundsWithScore = oQualifyRounds.GetPlayOffRoundByPlayerWithScore();
            //Calculamos los puntos


            RoundsWithScore.Sort(new ObjectComparer<PlayoffRound>("Machine_Number ASC, Score DESC", true));
            List<Player> oPlayers = new List<Player>(); //Donde almacenamos el total;
            if (RoundsWithScore.Count > 0)
            { //Si hay puntuaciones
                int CalculatingMachineFlag;//controla el cambio de máquina
                int CurrentMachineFlag;//controla el cambio de máquina
                int ScoreCounter = 0; // puntero a la puntuación
                CalculatingMachineFlag = RoundsWithScore[0].Machine_Number;
               
                //Calculamos los puntos por maquina y hacemos sumatorio
                for (int x = 0; x < RoundsWithScore.Count; x++)
                {
                    CurrentMachineFlag = RoundsWithScore[x].Machine_Number;
                    if (CurrentMachineFlag == CalculatingMachineFlag){
                        RoundsWithScore[x].PositionInRound = ScoreCounter + 1;
                      
                        
                        
                        //if (ScoreCounter < PlayoffRounds.Scores.Length)
                        //{  //si le toca puntuación
                        //    RoundsWithScore[x].PointsInRound = PlayoffRounds.Scores[ScoreCounter];
                            
                        //    ScoreCounter++;
                        //}
                        //else
                        //{
                        //    RoundsWithScore[x].PointsInRound = 0;
                        //}
                        if (ScoreCounter < Scores.Length)
                        {  //si le toca puntuación
                            RoundsWithScore[x].PointsInRound = Scores[ScoreCounter];
                            if (RoundsWithScore[x].Score == 0) //Si está penalizado
                            {
                                RoundsWithScore[x].PointsInRound = 0;
                                RoundsWithScore[x].PositionInRound = 0;
                            }
                            else
                            {
                                if (x > 0 && RoundsWithScore[x - 1].Score != RoundsWithScore[x].Score)
                                {//Verificamos si no es igual a la posicion anterior
                                    ScoreCounter++;
                                }
                                else if (x == 0)
                                {
                                    ScoreCounter++;
                                }
                                else
                                {
                                    //Repeticion de puntuaciones
                                    RoundsWithScore[x].PointsInRound = Scores[ScoreCounter - 1];
                                    RoundsWithScore[x].PositionInRound = ScoreCounter;
                                }
                            }
                        }
                        else
                        {
                            RoundsWithScore[x].PointsInRound = 0;
                            ScoreCounter++;
                        }
                        
                    }
                    else { //Cambiamos de máquina
                        ScoreCounter = 0;
                        RoundsWithScore[x].PointsInRound = Scores[ScoreCounter];
                        RoundsWithScore[x].PositionInRound = ScoreCounter + 1;
                        ScoreCounter++;
                        CalculatingMachineFlag = RoundsWithScore[x].Machine_Number;
                     
                    }
                }


                int CalculatingPlayerFlag;//controla el cambio de máquina
                int CurrentPlayerFlag;//controla el cambio de máquina
                RoundsWithScore.Sort(new ObjectComparer<PlayoffRound>("PlayerNumber ASC", true));
               
                CalculatingPlayerFlag = RoundsWithScore[0].PlayerNumber;
                Player oPlayer = new Player(RoundsWithScore[0].PlayerNumber, 0);
                oPlayers.Add(oPlayer);
                
                
                //Calculamos los puntos por maquina y hacemos sumatorio
                for (int x = 0; x < RoundsWithScore.Count; x++)
                {
                    CurrentPlayerFlag = RoundsWithScore[x].PlayerNumber;
                    if (CurrentPlayerFlag == CalculatingPlayerFlag)
                    {                       
                        oPlayers[oPlayers.Count - 1].PlayerScore += RoundsWithScore[x].PointsInRound;
                    }
                    else
                    { //Cambiamos de máquina

                        CalculatingPlayerFlag = RoundsWithScore[x].PlayerNumber;
                        oPlayer = new Player(RoundsWithScore[x].PlayerNumber, 0);
                        oPlayers.Add(oPlayer);
                        oPlayers[oPlayers.Count - 1].PlayerScore += RoundsWithScore[x].PointsInRound;
                    }
                }
                
            }
            RoundsWithScore.Sort(new ObjectComparer<PlayoffRound>("PlayerNumber ASC, Round_Number ASC", true));
            oPlayers.Sort(new ObjectComparer<Player>("PlayerScore DESC", true));
            Session["PORoundsWithScore"] = RoundsWithScore;
            Session["POoPlayers"] = oPlayers;
            Session["PORondas"] = Rondas;
            Session["POQualifyPlayersToPlayOffs"] = 4;

           
            //HTMLOUT = drawTable(RoundsWithScore, oPlayers, Rondas, oTournament.QualifyPlayersToPlayOffs );
            
 
    }
    public int getUniques(List<PlayoffRound> things)
    {
        Dictionary<int, bool> uniques = new Dictionary<int, bool>();
        foreach (PlayoffRound item in things)
        {
            if (!(uniques.ContainsKey(item.Pk_Player)))
            {
                uniques.Add(item.Pk_Player, true);
            }
        }
        return uniques.Count;
    }
    public string drawTable(List<PlayoffRound> oQualifyRounds, List<Player> o_Players, int p_RoundNumber, int p_QualifyPositions)
    {
        try
        {
            if (oQualifyRounds.Count > 0)
            {

                StringBuilder OutPutHTML = new StringBuilder();
                //OutPutHTML.Append("<table class=\"Lotery\" style=\"width:780px;text-align:left;border:1px solid black;border-collapse: collapse; padding:5px\">");
                OutPutHTML.Append("<table class=\"Lotery\" style=\"width:100%;text-align:left;border:1px solid black;border-collapse: collapse; padding:5px\">");
                OutPutHTML.Append("<tr style=\"background-color:#ffffff;border:1px solid black; font-weight:bold\">");
                //Header
                OutPutHTML.Append("<td></td>");
                OutPutHTML.Append("<td></td>");
                OutPutHTML.Append("<td>Player</td>");

                for (int x = 0; x < p_RoundNumber; x++)
                {
                    OutPutHTML.AppendFormat("<td>Round {0}</td>", x + 1);
                }
                OutPutHTML.Append("<td style=\"text-align:center\">Points</td>");

                int RowColor = 0;

                int Position = 1;

                Int64 CurrentScore = o_Players[0].PlayerScore;
                for (int x = 0; x < o_Players.Count; x++)
                {
                    

                        if (RowColor % 2 == 0)
                        {
                            OutPutHTML.Append("<tr style=\"background-color:#e6e4e4\">");
                        }
                        else
                        {
                            OutPutHTML.Append("<tr style=\"background-color:#ffffff\">");
                        }


                        //Pintamos el jugador
                        //Recorremos las rondas de ese jugador


                        List<PlayoffRound> oQualifyRoundsPerPlayer = oQualifyRounds.FindAll(delegate(PlayoffRound p) { return p.PlayerNumber == o_Players[x].Player_Number; });
                      

                        //Calculamos su posición
                        if (CurrentScore != o_Players[x].PlayerScore)
                        {
                            Position=x+1;
                        }

                        CurrentScore = o_Players[x].PlayerScore;
                     
                        if (Position <= p_QualifyPositions && x < p_QualifyPositions)
                        {
                            OutPutHTML.Append("<td style=\"text-align:center\"><img src=\"img/ico_ok.png\"></td>");
                        }
                        else if (Position <= p_QualifyPositions)
                        {
                            OutPutHTML.Append("<td style=\"text-align:center\"><img src=\"img/ico_wait.png\"></td>");
                        }
                        else
                        {
                            OutPutHTML.Append("<td style=\"text-align:center\"><img src=\"img/ico_not.png\"></td>");
                        }

                        OutPutHTML.AppendFormat("<td style=\"text-align:center\">{0}º</td>", Position);
                        OutPutHTML.AppendFormat("<td><b><img style=\"vertical-align:middle;\" src=\"img/player_flags/b{0}.png\"/> {1}</b> (#{2})</td>", oQualifyRoundsPerPlayer[0].Pk_Player_Zone, oQualifyRoundsPerPlayer[0].Player_Nick, oQualifyRoundsPerPlayer[0].PlayerNumber);

                        List<PlayoffRound> oPlayoffsRoundsFree;
                        //oPlayoffsRoundsFree = oQualifyRoundsPerPlayer.FindAll(delegate(QualifyRound p) { return p.Round_Number == -1; });
                        oPlayoffsRoundsFree = oQualifyRoundsPerPlayer.FindAll(delegate(PlayoffRound p) { return p.Round_Number == -1; });

                        for (int y = 0; y < p_RoundNumber; y++)
                        {

                            PlayoffRound oQualifyRoundsT = oQualifyRoundsPerPlayer.Find(delegate(PlayoffRound p) { return p.Round_Number == y + 1; });

                            if (oPlayoffsRoundsFree != null)
                            {
                                if (y < oPlayoffsRoundsFree.Count)
                                {
                                    if (oPlayoffsRoundsFree[y].IsJoker == true)
                                    {
                                        //OutPutHTML.AppendFormat("<td>{0} ({1}º) - {2} <img style=\"vertical-align:middle;width:15px\" src=\"img/joker.gif\"/></td>", oQualifyRoundsT.Machine_Acron, oQualifyRoundsT.PositionInRound, oQualifyRoundsT.Score);
                                        OutPutHTML.AppendFormat("<td>{0} ({1}º)<img style=\"vertical-align:middle;width:15px\" src=\"img/joker.gif\"/></td>", oPlayoffsRoundsFree[y].Machine_Acron, oPlayoffsRoundsFree[y].PositionInRound);
                                    }
                                    else
                                    {
                                        //OutPutHTML.AppendFormat("<td>{0} ({1}º) - {2}</td>", oQualifyRoundsT.Machine_Acron, oQualifyRoundsT.PositionInRound, oQualifyRoundsT.Score);
                                        OutPutHTML.AppendFormat("<td>{0} ({1}º)</td>", oPlayoffsRoundsFree[y].Machine_Acron, oPlayoffsRoundsFree[y].PositionInRound);
                                    }
                                }
                                else
                                {
                                    OutPutHTML.AppendFormat("<td></td>");
                                }         
                            }
                            else
                            {
                                if (oQualifyRoundsT != null)
                                {
                                    if (oQualifyRoundsT.IsJoker == true)
                                    {
                                        //OutPutHTML.AppendFormat("<td>{0} ({1}º) - {2} <img style=\"vertical-align:middle;width:15px\" src=\"img/joker.gif\"/></td>", oQualifyRoundsT.Machine_Acron, oQualifyRoundsT.PositionInRound, oQualifyRoundsT.Score );
                                        OutPutHTML.AppendFormat("<td>{0} ({1}º)<img style=\"vertical-align:middle;width:15px\" src=\"img/joker.gif\"/></td>", oQualifyRoundsT.Machine_Acron, oQualifyRoundsT.PositionInRound);
                                    }
                                    else
                                    {
                                        //OutPutHTML.AppendFormat("<td>{0} ({1}º) - {2}</td>", oQualifyRoundsT.Machine_Acron, oQualifyRoundsT.PositionInRound, oQualifyRoundsT.Score);
                                        OutPutHTML.AppendFormat("<td>{0} ({1}º)</td>", oQualifyRoundsT.Machine_Acron, oQualifyRoundsT.PositionInRound);
                                    }
                                }
                                else
                                {
                                    OutPutHTML.AppendFormat("<td></td>");
                                }
                            }

                        }
                        OutPutHTML.AppendFormat("<td style=\"text-align:center\">{0}</td>", o_Players[x].PlayerScore);
                        OutPutHTML.Append("</tr>");
                        RowColor++;

                    

                }



                OutPutHTML.Append("</table>");
                return OutPutHTML.ToString();
            }
            else
            {
                return string.Empty;
            }

        }
        catch (Exception) {
            return "ERROR";
        } 
    }

    [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.Read)]
    public string GetTable()
    {
        try
        {
            LoadData((int)Session["POPk_Tournament"]);

            string res = drawTable((List<PlayoffRound>)Session["PORoundsWithScore"], (List<Player>)Session["POoPlayers"], (int)Session["PORondas"], (int)Session["PlayoffQualifyPossitions"]);
          
            return res;
        }
        catch(Exception)
        {
            return string.Empty;
        }
    }
}

